package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1号  请求头中的用户ID  传递给 2号
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            if (request != null) {
                //获取真实用户ID
                String userId = request.getHeader("userId");
                if (!StringUtils.isEmpty(userId)) {
                    requestTemplate.header("userId", userId);
                }
                //获取临时用户ID
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userTempId)) {
                    requestTemplate.header("userTempId", userTempId);
                }
            }
        }
    }

}
